/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.2012-12-07
 */
package com.yunhoo.pay.bean;

import com.ibatis.dao.client.DaoManager;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.yunhoo.asset.util.PayCodeConstants;
import com.yunhoo.base.bean.FinancialProjectBean;
import com.yunhoo.base.db.dao.DepartmentDao;
import com.yunhoo.base.db.dao.FinancialProjectDao;
import com.yunhoo.base.db.dao.PersonDao;
import com.yunhoo.base.db.impl.BusinessParameterImpl;
import com.yunhoo.base.model.AbroadGroupCurrency;
import com.yunhoo.base.model.AbroadGroupGroup;
import com.yunhoo.base.model.ClassCode;
import com.yunhoo.base.model.Department;
import com.yunhoo.base.model.FinancialProject;
import com.yunhoo.base.model.PayStyle;
import com.yunhoo.base.model.Person;
import com.yunhoo.pay.db.impl.AbroadGroupCheckImpl;
import com.yunhoo.pay.db.impl.AbroadGroupImpl;
import com.yunhoo.pay.db.impl.VoucherPubImpl;
import com.yunhoo.pay.model.AbroadGroupBackorCollar;
import com.yunhoo.pay.model.AbroadGroupCost;
import com.yunhoo.pay.model.Expense;
import com.yunhoo.pay.model.QueryVouchers;
import com.yunhoo.pay.model.VouCheckInfo;
import com.yunhoo.pay.util.BillNumBuilder;
import com.yunhoo.sys.db.config.DaoConfig;
import com.yunhoo.sys.util.common.Disabled;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.NavigationTool;
import com.yunhoo.sys.util.common.Null;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.login.LoginBean;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.richfaces.component.UIDataTable;
import org.richfaces.event.TreeSelectionChangeEvent;

/**
 *
 * 出国差旅费报销单
 *
 * @author Administrator
 */
@ManagedBean(name = "abroadGroupBean")
@SessionScoped
public class AbroadGroupBean {

    private Expense abroad = null;                         //主表   
    private AbroadGroupCost cost = null;                   //费用明细表
    private AbroadGroupCurrency currency = null;           //币种表
    private AbroadGroupGroup group = null;                 //出国团组表
    private AbroadGroupBackorCollar back = null;           //退领表
    private List<AbroadGroupCost> costLi = null;           //费用明细表list
    private DataModel<AbroadGroupCost> costModel = null;
    private DataModel<AbroadGroupBackorCollar> backModel = null;
    private List<AbroadGroupBackorCollar> backLi = null;    //退领表list
    private List<AbroadGroupGroup> groupLi = null;
    private List<AbroadGroupCurrency> currencyLi = null;
    private List<PayStyle> payStyleli = null;
    private int costLiSize;                                 //用于页面js的反写定位
    private boolean showAble = true;
    private boolean addOrUpdate = false;
    private boolean deleteable = false;
    private boolean saveOrNot = false;
    private boolean updateOrNot = false;
    private boolean submitOrNot = false;
    private boolean printAble = false;
    private boolean browAble = false;
    private Disabled dis = new Disabled();
    private String payWay;
    private List<SelectItem> payStyleList;
    private UIDataTable deptData = null;
    private List<Department> deptli = null;
    private DataModel deptModel = new ListDataModel();
    private QueryVouchers qta = new QueryVouchers();
    private List<Expense> abroadList = null;
    private DataModel abroadModel = new ListDataModel();
    private LinkedList<Expense> linkedli = new LinkedList<Expense>();
    //private List<Expense> abroadList = null;
    //private DataModel abroadModel = null;
    private ClassCode classcode = new ClassCode();
    private List<ClassCode> classlist = new ArrayList();
    private int index;
    private static DaoManager daom;
    private static DepartmentDao dao;
    private static FinancialProjectDao finProjdao;
    private FinancialProject finProj = null;
    private DataModel<FinancialProject> finProjModel = null;
    private String projParam = "";
    private List<SelectItem> perli = null;
    private static PersonDao perDao;

    public AbroadGroupBean() {
        daom = DaoConfig.getDaoManager();
        dao = (DepartmentDao) daom.getDao(DepartmentDao.class);
        finProjdao = (FinancialProjectDao) daom.getDao(FinancialProjectDao.class);
        perDao = (PersonDao) daom.getDao(PersonDao.class);
        initProperty();
        initFunction();
        initStatus();
        initPayStyleList();
        initReportList();
        initFinProjList();//预算项目列表
    }

    //初始化状态属性
    public final void initStatus() {
        saveOrNot = true;
        addOrUpdate = false;
        deleteable = true;
        updateOrNot = true;
        submitOrNot = true;
        showAble = true;
        printAble = true;
    }

    //属性初始化
    public final void initProperty() {
        abroad = new Expense();
        cost = new AbroadGroupCost();
        currency = new AbroadGroupCurrency();
        group = new AbroadGroupGroup();
        back = new AbroadGroupBackorCollar();
        abroadModel = new ListDataModel();
    }

    //方法初始化
    public final void initFunction() {
        groupLi = AbroadGroupImpl.getAbroadGroupGroup();
        currencyLi = AbroadGroupImpl.getAbroadGroupCurrency();
        for (AbroadGroupCurrency cur : currencyLi) {
            cur.setSign(new String(cur.getSign().trim().toCharArray()));
        }
        costLi = new ArrayList();
        backLi = new ArrayList();
        for (int i = 0; i < 2; i++) {
            AbroadGroupCost ac = new AbroadGroupCost();
            AbroadGroupBackorCollar ab = new AbroadGroupBackorCollar();
            //ac.setLineId(i + 1);
            //ab.setLineId(i + 1);
            costLi.add(ac);
            backLi.add(ab);
        }
        costLiSize = costLi.size();
        costModel = new ListDataModel(costLi);
        backModel = new ListDataModel(backLi);
    }

    //单据列表初始化
    public final void initReportList() {
        linkedli = new LinkedList();
        Map map = new HashMap();
        map.put("person", curPerNum().trim());
        map.put("orgCode", curOrgCode().trim());
        abroadList = AbroadGroupImpl.getAbroadPersonList(map);
        //abroadModel.setWrappedData(abroadList);
        linkedli.addAll(abroadList);
    }

    //选择部门
    public void selected(TreeSelectionChangeEvent event) {
        Department dp = (Department) TreeUtil.listener(event);
        abroad.getPayDept().setCode(dp.getCode());
        abroad.getPayDept().setName(dp.getName());
        if (!Null.check(abroad.getPayDept().getCode())) {
            queryPerLi();
        }
    }

    private void queryPerLi() {
        perli = new ArrayList<SelectItem>();
        List<Person> templi = null;
        try {
            Person param = new Person();
            param.setOrgCode(curOrgCode());
            param.setIyear(curIyear());
            param.setDeptCode(abroad.getPayDept().getCode());
            templi = perDao.queryListByDept(param);
            //templi = perDao.queryAll();
        } catch (SQLException ex) {
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (templi != null) {
            for (Person p : templi) {
                perli.add(new SelectItem(p.getCpsn_number().trim(), p.getCpsn_name().trim()));
            }
        }
    }

    private void initFinProjList() {
        if (finProjModel == null) {
            finProjModel = new ListDataModel<FinancialProject>();
        }
        try {
            List<FinancialProject> finli = finProjdao.queryAll(new FinancialProject(true));
            finProjModel.setWrappedData(finli);
        } catch (SQLException ex) {
            Logger.getLogger(FinancialProjectBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //选择预算项目
    public void projSelected() {
        finProj = finProjModel.getRowData();
        abroad.getProject().setFinCode(finProj.getFinCode());
        abroad.getProject().setFinName(finProj.getFinName());
        abroad.getProject().setCostType(finProj.getCostType());
    }

    //支付方式选择列表
    public final void initPayStyleList() {
        List<PayStyle> Styleli = AbroadGroupImpl.getPaystyleliNew("6");
        payStyleList = new ArrayList();
        for (PayStyle d : Styleli) {
            payStyleList.add(new SelectItem(d.getCode(), d.getName()));
        }
    }

    //获取cost and back model
    public void initCostAndBanckModel() {
        Map map = new HashMap();
        map.put("number", abroad.getNumber().trim());
        map.put("voutype", "6");
        map.put("orgCode", curOrgCode().trim());
        costLi = AbroadGroupCheckImpl.getAbroadCostLi(map);
        backLi = AbroadGroupCheckImpl.getAbroadBackLi(map);
        for (int i = 0; i < costLi.size(); i++) {
            //costLi.get(i).setLineId(i + 1);
            if (costLi.get(i).getStayCost() == 0) {
                costLi.get(i).setStayCost(null);
            }
            if (costLi.get(i).getFoodCost() == 0) {
                costLi.get(i).setFoodCost(null);
            }
            if (costLi.get(i).getMixCost() == 0) {
                costLi.get(i).setMixCost(null);
            }
            if (costLi.get(i).getPersonalCost() == 0) {
                costLi.get(i).setPersonalCost(null);
            }
            if (costLi.get(i).getTrafficCost() == 0) {
                costLi.get(i).setTrafficCost(null);
            }
            if (costLi.get(i).getOther() == 0) {
                costLi.get(i).setOther(null);
            }
        }
        for (int i = 0; i < backLi.size(); i++) {
            //backLi.get(i).setLineId(i + 1);
            if (backLi.get(i).getAdvance() == 0) {
                backLi.get(i).setAdvance(null);
            }
            if (backLi.get(i).getAmount() == 0) {
                backLi.get(i).setAmount(null);
            }
        }
        for (int i = 0; i < costLi.size() - backLi.size(); i++) {
            backLi.add(new AbroadGroupBackorCollar());
        }
        costModel.setWrappedData(costLi);
        backModel.setWrappedData(backLi);
    }

    public void getFirst() {
        if (linkedli.size() == 0) {
            if (abroadList.isEmpty()) {
                //System.out.println("您尚未录入单据!");
                ToolKit.msgs_info("您尚未录入单据!");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(abroadList);
                this.setAbroad(linkedli.getFirst());
                abroad.setPerson(abroad.getUser().getCpsn_name());
                payWay = abroad.getPayStyle().getCode();
                queryPerLi();
                initCostAndBanckModel();

                dis.setFirst(true);
                dis.setPreviouse(true);
                dis.setNext(false);
                dis.setLast(false);
            }
        } else {
            this.setAbroad(linkedli.getFirst());
            payWay = abroad.getPayStyle().getCode();
            queryPerLi();
            initCostAndBanckModel();

            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
            browAble = true;
        }
        if (abroad.getNumberStatus().trim().equals("0")) {
            submitOrNot = true;
        } else {
            submitOrNot = false;
            deleteable = false;
            updateOrNot = false;
        }
        printAble = false;
        index = 0;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void getLast() {
        if (linkedli.size() == 0) {
            if (abroadList.isEmpty()) {
                //System.out.println("您尚未录入单据!");
                ToolKit.msgs_info("您尚未录入单据!");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(abroadList);
                this.setAbroad(linkedli.getLast());
                abroad.setPerson(abroad.getUser().getCpsn_name());
                payWay = abroad.getPayStyle().getCode();
                queryPerLi();
                initCostAndBanckModel();

                dis.setLast(true);
                dis.setNext(true);
                dis.setPreviouse(false);
                dis.setFirst(false);
            }
        } else {
            this.setAbroad(linkedli.getLast());
            payWay = abroad.getPayStyle().getCode();
            queryPerLi();
            browAble = true;
            initCostAndBanckModel();

            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        if (abroad.getNumberStatus().trim().equals("0")) {
            submitOrNot = true;
        } else {
            submitOrNot = false;
            deleteable = false;
            updateOrNot = false;
        }
        printAble = false;
        index = linkedli.size() - 1;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void next() {
        if (index < linkedli.size() - 1) {
            index++;
            this.setAbroad(linkedli.get(index));
            abroad.setPerson(abroad.getUser().getCpsn_name());
            payWay = abroad.getPayStyle().getCode();
            queryPerLi();
            browAble = true;
            initCostAndBanckModel();

            dis.setFirst(false);
            dis.setPreviouse(false);
        } else {
            //System.out.println("没有了!");
            ToolKit.msgs_info("没有了!");
            dis.setLast(true);
            dis.setNext(true);
            dis.setFirst(false);
            dis.setPreviouse(false);
        }
        if (abroad.getNumberStatus().trim().equals("0")) {
            submitOrNot = true;
        } else {
            submitOrNot = false;
            deleteable = false;
            updateOrNot = false;
        }
        printAble = false;
        FacesContext.getCurrentInstance().renderResponse();
        //System.out.println("submitOrNot: " + submitOrNot);
    }

    public void previouse() {
        if (index > 0) {
            index -= 1;
            this.setAbroad(linkedli.get(index));
            abroad.setPerson(abroad.getUser().getCpsn_name());
            browAble = true;
            payWay = abroad.getPayStyle().getCode();
            queryPerLi();
            initCostAndBanckModel();

            dis.setNext(false);
            dis.setLast(false);
        } else {
            //System.out.println("没有了!");
            ToolKit.msgs_info("没有了!");
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
            FacesContext.getCurrentInstance().renderResponse();
        }
        if (abroad.getNumberStatus().trim().equals("0")) {
            submitOrNot = true;
        } else {
            submitOrNot = false;
            deleteable = false;
            updateOrNot = false;
        }
        printAble = false;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void add() {
        saveOrNot = false;
        showAble = false;
        printAble = true;
        addOrUpdate = true;
        deleteable = true;
        updateOrNot = true;
        submitOrNot = true;
        browAble = false;
        abroad = new Expense();
        abroad.getUser().setCpsn_name(curPerName().trim());
        abroad.getDept().setName(curDeptName().trim());
        abroad.getPayDept().setCode(curDeptCode().trim());
        abroad.getPayDept().setName(curDeptName().trim());
        abroad.setNumDate(curLoginDate());
        //abroad.setNumber(ToolsMethed.getAgroupMaxNumber());
        abroad.setPerson(curPerName().trim());
        abroad.getFeePer().setCpsn_number(curPerNum().trim());
        queryPerLi();
        initFunction();
    }

    public void update() {
        showAble = false;
        addOrUpdate = false;
        saveOrNot = false;
        browAble = false;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void cancel() {
        abroad = new Expense();
        qta = new QueryVouchers();
        initFunction();
        initStatus();
        if (!linkedli.isEmpty()) {
            dis.setFirst(false);
            dis.setLast(false);
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    //删除
    public void delete() {
        int flag = 0;
        SqlMapClient client = IbatisTemplate.getSqlMapClient();
        try {
            client.startTransaction();
            AbroadGroupImpl.deletefrompayVouchers(client, abroad.getNumber().trim());
            AbroadGroupImpl.deleteAbroadGroupCostLi(client, abroad.getNumber().trim());
            AbroadGroupImpl.deleteAbroadGroupBackLi(client, abroad.getNumber().trim());
            client.commitTransaction();
            flag = 1;
        } catch (SQLException e) {
            flag = -1;
            System.out.println(e.getMessage());
        } finally {
            try {
                client.endTransaction();
            } catch (SQLException ex) {
                Logger.getLogger(AbroadGroupBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        if (flag == 1) {
            initReportList();
            initStatus();
            initProperty();
            initFunction();
            initPayStyleList();
            ToolKit.msgs_info("删除成功!");
        } else if (flag == -1) {
            ToolKit.msgs_err("数据库异常，删除失败");
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    //提交
    public void submitBill() {
        abroad.setNumberStatus("0");
        Map map = new HashMap();
        map.put("voustatus", "0");
        map.put("voutype", abroad.getVoutype().trim());
        map.put("number", abroad.getNumber());
        map.put("orgCode", curOrgCode().trim());
        AbroadGroupImpl.updateVouStatus(map);
        //删除历史审核信息
        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(abroad.getNumber());
        info.setVouType(abroad.getVoutype());
        VoucherPubImpl.deleteCheckInfo(info);
        initStatus();
        printAble = false;
        ToolKit.msgs_info("单据已提交成功，等待审核!");
    }

    //返回单据列表
    public void goback() {
        initReportList();
        NavigationTool.getSelectedUrl("/page/pay/business/person/queryAbroadGroupList.xhtml");
        FacesContext.getCurrentInstance().renderResponse();
    }

    //撤单
    public void rescind() {
        Map map = new HashMap();
        map.put("voustatus", "1");
        map.put("voutype", abroad.getVoutype().trim());
        map.put("number", abroad.getNumber().trim());
        map.put("orgCode", curOrgCode().trim());
        AbroadGroupImpl.updateVouStatus(map);
        addOrUpdate = false;
        abroad.setNumberStatus("1");
    }

    //单据列表Selected
    public void showPersonDetail() {
        initStatus();
        addOrUpdate = false;
        updateOrNot = false;
        showAble = true;
        abroad = (Expense) abroadModel.getRowData();
        abroad.setPerson(abroad.getUser().getCpsn_name());
        payWay = abroad.getPayStyle().getCode();
        queryPerLi();

        initCostAndBanckModel();
        abroadModel.setWrappedData(new ArrayList<Expense>());

        if (abroad.getNumberStatus().trim().equals("0")) {
            submitOrNot = true;
        } else {
            submitOrNot = false;    //false: 提交可用
            deleteable = false;     //false: (未提交)删除可用
        }
        printAble = false;      //false: 打印可用

        NavigationTool.getSelectedUrl("/page/pay/business/person/abroadGroup.xhtml");
    }

    //选择预算项目
    public void selectProjForQuery() {
        FinancialProject fProj = finProjModel.getRowData();
        qta.getProject().setFinCode(fProj.getFinCode());
        qta.getProject().setFinName(fProj.getFinName());
    }

    //选择部门
    public void selecteDeptForQuery(TreeSelectionChangeEvent event) {
        Department dp = (Department) TreeUtil.listener(event);
        qta.getDept().setCode(dp.getCode());
        qta.getDept().setName(dp.getName());
    }
    //单据列表查询

    public void queryAbroadList() {
        //System.out.println("costcode:" + qta.getCostitem().getCode());
        Map map = new HashMap();
        map.put("person", curPerNum().trim());
        map.put("orgCode", curOrgCode().trim());
        map.put("number", qta.getNumber().trim());
        map.put("affair", qta.getAffair().trim());
        map.put("projcode", qta.getProject().getFinCode());
        map.put("deptname", qta.getDept().getName().trim());
        map.put("cpsn_name", qta.getUser().getCpsn_number().trim());
        map.put("budgetSource", qta.getBudgetSource().trim());
        map.put("costcode", Null.convert(qta.getCostitem().getCode()).trim());
        map.put("paycode", qta.getPaycode().trim());
        map.put("costClass", qta.getCostClass().trim());
        map.put("costType", qta.getCostTypes().getCode().trim());
        map.put("payStyle", qta.getPayStyle().trim());
        map.put("ticketcode", qta.getTicketcode().trim());
        map.put("numDateStart", qta.getNumDateStart());
        map.put("numDateEnd", qta.getNumDateEnd());
        map.put("auditDateStart", qta.getAuditDateStart());
        map.put("auditDateEnd", qta.getAuditDateEnd());
        map.put("payDateStart", qta.getPayDateStart());
        map.put("payDateEnd", qta.getPayDateEnd());
        map.put("totalStart", qta.getTotalStart());
        map.put("totalEnd", qta.getTotalEnd());
        map.put("checkaccountStart", qta.getCheckaccountStart());
        map.put("checkaccountEnd", qta.getCheckaccountEnd());
        map.put("payaccountStart", qta.getPayaccountStart());
        map.put("payaccountEnd", qta.getPayaccountEnd());
        abroadList = AbroadGroupImpl.getAbroadPersonList(map);
        abroadModel.setWrappedData(abroadList);
    }

    public void clearQueryResult(ActionEvent e) {
        abroadModel.setWrappedData(new ArrayList<Expense>());
    }
    //增行

    public void addLine() {
        addCost();
        addBack();
    }

    //费用明细表新增行
    public void addCost() {
        AbroadGroupCost ac = new AbroadGroupCost();
        //ac.setLineId(costLi.size() + 1);
        costLi.add(ac);
        costLiSize = costLi.size();
        costModel.setWrappedData(costLi);
    }

    //退领表新增行
    public void addBack() {
        AbroadGroupBackorCollar ac = new AbroadGroupBackorCollar();
        //ac.setLineId(backLi.size() + 1);
        backLi.add(ac);
        backModel.setWrappedData(backLi);
    }

    //合计
    public void setTotalAccount() {
        List<AbroadGroupCost> coLi = (ArrayList) costModel.getWrappedData();
        List<AbroadGroupBackorCollar> bcli = (ArrayList) backModel.getWrappedData();
        Double costTotal = 0d;
        Double advanceTotal = 0d;
        for (int i = 0; i < coLi.size(); i++) {
            costTotal += Null.convert(coLi.get(i).getFoodCost()) + Null.convert(coLi.get(i).getMixCost()) + Null.convert(coLi.get(i).getOther()) + Null.convert(coLi.get(i).getPersonalCost()) + Null.convert(coLi.get(i).getStayCost()) + Null.convert(coLi.get(i).getTrafficCost());
            advanceTotal += Null.convert(bcli.get(i).getAdvance());
        }
        abroad.setTotal(costTotal - advanceTotal);
    }

    //保存检测
    public void checkSave() {
        projParam = "1";
        String paramValue = BusinessParameterImpl.queryParamValue(projParam.trim());//1、必填 0、可不必须填写
        int flag = 0;

        if (abroad.getNumDate() == null) {
            ToolKit.msgs_err("请选择填单日期!");
        } else if (Null.check(abroad.getAffair())) {
            ToolKit.msgs_err("请填写出国事由!");
        } else if (Null.check(abroad.getGroup().getCountry())) {
            ToolKit.msgs_err("请填写国家!");
        } else if (Null.check(abroad.getGroup().getMember())) {
            ToolKit.msgs_err("请填写团组人员列表!");
        } else if (Null.check(abroad.getProject().getFinCode()) && paramValue.equals("1")) {
            ToolKit.msgs_err("请选择预算项目!");
        } else if (Null.check(abroad.getFeePer().getCpsn_number())) {
            ToolKit.msgs_err("请选择报销人!");
        } else if (Null.check(payWay)) {
            ToolKit.msgs_err("请选择支付方式!");
        } else if (abroad.getGroup().getStartDate() == null) {
            ToolKit.msgs_err("请填写出国日期!");
        } else if (abroad.getGroup().getEndDate() == null) {
            ToolKit.msgs_err("请填写返回日期!");
        } else if (checkCostModel() == true) {
            ToolKit.msgs_err("请填写费用明细!");
        } else if (Null.check(abroad.getAffixAmount())) {
            ToolKit.msgs_err("请填写附件张数!");
        } else {
            SqlMapClient client = IbatisTemplate.getSqlMapClient();
            try {
                client.startTransaction();
                // save();
                /* save start */

                //保存出国差旅费报销单
                setTotalAccount();      //生成合计
                if (addOrUpdate) {
                    abroad.setVoutype("6");

                    //String number = AbroadGroupImpl.getAgroupMaxNumber(client);
                    String number = BillNumBuilder.buildNum(client);
                    abroad.setNumber(number);

                    AbroadGroupImpl.insertAbroadGroup(client, buildExpMap());
                } else {
                    AbroadGroupImpl.updateAbroadGroup(client, buildExpMap());
                }
                //保存出国团组
                if (addOrUpdate) {
                    AbroadGroupImpl.insertAbroadGroupGroup(client, buildGroupMap());   //插入出国团组
                } else {
                    AbroadGroupImpl.updateAbroadGroupGroup(client, buildGroupMap());
                }
                /* save end */

                //saveCost();
                /* saveCost start */

                Map costMap = new HashMap();
                List<AbroadGroupCost> coLi = (ArrayList) costModel.getWrappedData();
                AbroadGroupImpl.deleteAbroadGroupCostLi(client, abroad.getNumber().trim());
                for (AbroadGroupCost ct : coLi) {
                    Double[] arr = Null.convert(new Double[]{ct.getStayCost(), ct.getFoodCost(), ct.getMixCost(), ct.getPersonalCost(), ct.getTrafficCost(), ct.getOther()});
                    Double total = arr[0] + arr[1] + arr[2] + arr[3] + arr[4] + arr[5];
                    if (!Null.check(ct.getCurrency().getCode()) && total != 0) {
                        costMap.put("orgCode", curOrgCode().trim());
                        costMap.put("number", abroad.getNumber().trim());
                        costMap.put("currency", ct.getCurrency().getCode());
                        costMap.put("stayCost", arr[0]);
                        costMap.put("foodCost", arr[1]);
                        costMap.put("mixCost", arr[2]);
                        costMap.put("personalCost", arr[3]);
                        costMap.put("trafficCost", arr[4]);
                        costMap.put("other", arr[5]);
                        if (addOrUpdate) {
                            AbroadGroupImpl.insertAbroadGroupCost(client, costMap);      //插入费用明细
                        } else {
                            //AbroadGroupImpl.updateAbroadGroupCost(costMap);                    
                            AbroadGroupImpl.insertAbroadGroupCost(client, costMap);      //插入费用明细
                        }
                    }
                }

                /* saveCost end */

                //saveBack();
                /* saveBack start */

                Map backMap = new HashMap();
                List<AbroadGroupBackorCollar> bcli = (ArrayList) backModel.getWrappedData();
                AbroadGroupImpl.deleteAbroadGroupBackLi(client, abroad.getNumber().trim());
                Double advance;
                Double amount;
                for (AbroadGroupBackorCollar bl : bcli) {
                    advance = Null.convert(bl.getAdvance());
                    amount = Null.convert(bl.getAmount());
                    if (!Null.check(bl.getCurrency().getCode()) && bl.getSign() != null && (advance != 0 || amount != 0)) {
                        backMap.put("orgCode", curOrgCode().trim());
                        backMap.put("number", abroad.getNumber().trim());
                        backMap.put("currency", bl.getCurrency().getCode().trim());
                        backMap.put("advance", advance);
                        backMap.put("sing", bl.getSign().trim());
                        backMap.put("amount", amount);
                        if (addOrUpdate) {
                            AbroadGroupImpl.insertAbroadGroupBackorCollar(client, backMap);     //插入退领明细
                        } else {
                            //AbroadGroupImpl.updateAbroadGroupBackorCollar(backMap);                    
                            AbroadGroupImpl.insertAbroadGroupBackorCollar(client, backMap);     //插入退领明细
                        }
                    }
                }

                /* saveBack end */



                client.commitTransaction();

                System.out.println(" after commit ");
                flag = 1;

            } catch (SQLException e) {

                System.out.println("save err ");

                flag = -1;
                
                e.printStackTrace();

            } finally {
                try {
                    client.endTransaction();
                } catch (SQLException ex) {
                    Logger.getLogger(AbroadGroupBean.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        if (flag == 1) {
            initCostAndBanckModel();
            ToolKit.msgs_info("请点击【提交】按钮提交单据并打印本单据!");
            abroad.setNumberStatus("1");
            browAble = true;
            saveOrNot = true;       //false: 保存可用
            //addOrUpdate = true;   //true:  新增  false: 修改
            deleteable = false;     //false: 删除可用
            updateOrNot = false;    //false: 修改可用
            submitOrNot = false;    //false: 提交可用
            showAble = true;        //false: 表单可用
            printAble = false;      //false: 打印可用
            addOrUpdate = false;    //修改可用..
            initReportList();
        } else if (flag == -1) {
            ToolKit.msgs_err("数据库异常，保存失败!");
        }
    }

    //保存
    public void save() {
        //保存出国差旅费报销单
        setTotalAccount();      //生成合计
        if (addOrUpdate) {
            abroad.setVoutype("6");
            AbroadGroupImpl.insertAbroadGroup(buildExpMap());
        } else {
            AbroadGroupImpl.updateAbroadGroup(buildExpMap());
        }
        //保存出国团组
        if (addOrUpdate) {
            AbroadGroupImpl.insertAbroadGroupGroup(buildGroupMap());   //插入出国团组
        } else {
            AbroadGroupImpl.updateAbroadGroupGroup(buildGroupMap());
        }
        showAble = true;
        browAble = true;
    }

    public Map buildExpMap() {
        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        map.put("number", abroad.getNumber().trim());
        map.put("deptcode", curDeptCode().trim());
        map.put("voudate", abroad.getNumDate());
        map.put("totalaccount", Null.convert(abroad.getTotal()));
        map.put("affair", abroad.getAffair().trim());
        map.put("person", curPerNum().trim());
        map.put("auditor", Null.convert(abroad.getAuditor()));
        map.put("payer", Null.convert(abroad.getPayer()));
        map.put("memo", abroad.getMemo().trim());
        map.put("voustatus", "1");
        map.put("voutype", abroad.getVoutype());
        map.put("abroadGroup", abroad.getNumber().trim());
        map.put("payStyle", payWay);
        map.put("payDept", abroad.getPayDept().getCode());
        map.put("feePerson", abroad.getFeePer().getCpsn_number().trim());
        map.put("affixAmount", abroad.getAffixAmount());
        map.put("projCode", Null.convert(abroad.getProject().getFinCode()));
        return map;
    }

    public Map buildGroupMap() {
        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        map.put("code", abroad.getNumber().trim());
        map.put("name", abroad.getGroup().getName());
        map.put("country", abroad.getGroup().getCountry());
        map.put("menber", abroad.getGroup().getMember());
        map.put("startDate", abroad.getGroup().getStartDate());
        map.put("endDate", abroad.getGroup().getEndDate());
        return map;
    }

    //保存费用明细
    public void saveCost() {
        Map costMap = new HashMap();
        List<AbroadGroupCost> coLi = (ArrayList) costModel.getWrappedData();
        AbroadGroupImpl.deleteAbroadGroupCostLi(abroad.getNumber().trim());
        for (AbroadGroupCost ct : coLi) {
            Double[] arr = Null.convert(new Double[]{ct.getStayCost(), ct.getFoodCost(), ct.getMixCost(), ct.getPersonalCost(), ct.getTrafficCost(), ct.getOther()});
            Double total = arr[0] + arr[1] + arr[2] + arr[3] + arr[4] + arr[5];
            if (!Null.check(ct.getCurrency().getCode()) && total != 0) {
                costMap.put("orgCode", curOrgCode().trim());
                costMap.put("number", abroad.getNumber().trim());
                costMap.put("currency", ct.getCurrency().getCode());
                costMap.put("stayCost", arr[0]);
                costMap.put("foodCost", arr[1]);
                costMap.put("mixCost", arr[2]);
                costMap.put("personalCost", arr[3]);
                costMap.put("trafficCost", arr[4]);
                costMap.put("other", arr[5]);
                if (addOrUpdate) {
                    AbroadGroupImpl.insertAbroadGroupCost(costMap);      //插入费用明细
                } else {
                    //AbroadGroupImpl.updateAbroadGroupCost(costMap);                    
                    AbroadGroupImpl.insertAbroadGroupCost(costMap);      //插入费用明细
                }
            }
        }
    }

    //保存退领明细
    public void saveBack() {
        Map backMap = new HashMap();
        List<AbroadGroupBackorCollar> bcli = (ArrayList) backModel.getWrappedData();
        AbroadGroupImpl.deleteAbroadGroupBackLi(abroad.getNumber().trim());
        Double advance;
        Double amount;
        for (AbroadGroupBackorCollar bl : bcli) {
            advance = Null.convert(bl.getAdvance());
            amount = Null.convert(bl.getAmount());
            if (!Null.check(bl.getCurrency().getCode()) && bl.getSign() != null && (advance != 0 || amount != 0)) {
                backMap.put("orgCode", curOrgCode().trim());
                backMap.put("number", abroad.getNumber().trim());
                backMap.put("currency", bl.getCurrency().getCode().trim());
                backMap.put("advance", advance);
                backMap.put("sing", bl.getSign().trim());
                backMap.put("amount", amount);
                if (addOrUpdate) {
                    AbroadGroupImpl.insertAbroadGroupBackorCollar(backMap);     //插入退领明细
                } else {
                    //AbroadGroupImpl.updateAbroadGroupBackorCollar(backMap);                    
                    AbroadGroupImpl.insertAbroadGroupBackorCollar(backMap);     //插入退领明细
                }
            }
        }
    }

    //生成出国团组code
    public String autoGroupCode() {
        String maxCode = AbroadGroupImpl.getAbroadGroupGroupMaxCode();
        if (Null.check(maxCode)) {
            maxCode = "0";
        }
        String str = String.format("%05d%n", Integer.parseInt(maxCode.trim()) + 1);
        return str.trim();
    }

    //费用明细NullCheck
    public boolean checkCostModel() {
        Boolean costModelisNull = true;
        List<AbroadGroupCost> coLi = (ArrayList) costModel.getWrappedData();
        Double total;
        for (AbroadGroupCost ct : coLi) {
            Double arr[] = Null.convert(new Double[]{ct.getStayCost(), ct.getFoodCost(), ct.getMixCost(), ct.getPersonalCost(), ct.getTrafficCost(), ct.getOther()});
            total = arr[0] + arr[1] + arr[2] + arr[3] + arr[4] + arr[5];
            if (!Null.check(ct.getCurrency().getCode()) && !Null.check(ct.getCurrency().getName()) && total != 0) {
                costModelisNull = false;
            }
        }
        return costModelisNull;
    }

    //退领明细NullCheck
    public boolean checkBackModel() {
        Boolean backModelisNull = true;
        List<AbroadGroupBackorCollar> bcli = (ArrayList) backModel.getWrappedData();
        for (AbroadGroupBackorCollar bl : bcli) {
            Double arr[] = Null.convert(new Double[]{bl.getAdvance(), bl.getAmount()});
            if (!Null.check(bl.getCurrency().getCode()) && !Null.check(bl.getCurrency().getName()) && (arr[0] != 0 || arr[1] != 0)) {
                backModelisNull = false;
            }
        }
        return backModelisNull;
    }

    //单行删除 设置行号
    public void delLine() {
        int lineId = costModel.getRowIndex();
        costLi.remove(lineId);
        if (backLi.size() > lineId) backLi.remove(lineId);
        costLiSize--;
    }

    //单据号自动生成
    public static String getMaxNumber() {
        String MaxNum = (String) AbroadGroupImpl.getMaxNum().trim();
        if (MaxNum == null || MaxNum.length() == 0) {
            MaxNum = "000001";
            return MaxNum;
        }
        MaxNum = String.format("%06d%n", Integer.parseInt(MaxNum.trim()) + 1);
        return MaxNum;
    }

    //自动生成合计值
    public void autoValue() {
        Double total;
        List<AbroadGroupCost> coLi = (ArrayList) costModel.getWrappedData();
        List<AbroadGroupBackorCollar> bcli = (ArrayList) backModel.getWrappedData();
        Double stay;
        Double food;
        Double mix;
        Double personal;
        Double traffic;
        Double other;
        Double advance;
        for (int i = 0; i < coLi.size(); i++) {
            stay = Null.convert(coLi.get(i).getStayCost());
            food = Null.convert(coLi.get(i).getFoodCost());
            mix = Null.convert(coLi.get(i).getMixCost());
            personal = Null.convert(coLi.get(i).getPersonalCost());
            traffic = Null.convert(coLi.get(i).getTrafficCost());
            other = Null.convert(coLi.get(i).getOther());
            advance = Null.convert(bcli.get(i).getAdvance());

            total = stay + food + mix + personal + traffic + other;

            if ((advance - total) >= 0) {
                bcli.get(i).setSign("退");
                bcli.get(i).setAmount(advance - total);
            } else {
                bcli.get(i).setSign("领");
                bcli.get(i).setAmount(total - advance);
            }
        }
    }

    public void process(OutputStream outStream, Object data) throws Exception {
        print();
    }

    public void print() throws Exception {
        Map map = reportParameter();//parameters
        ArrayList jasperPrintList = new ArrayList();
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ServletContext scontext = (ServletContext) facesContext.getExternalContext().getContext();
        map.put("SUBREPORT_DIR", scontext.getRealPath("/page/pay/print/abroadTravelCost_subreport1.jasper"));
        map.put("costDetail_jasper", scontext.getRealPath("/page/pay/print/abroadTravelCost_subreport2.jasper"));
        List templi = new ArrayList();
        for (AbroadGroupCost ct : costLi) {
            if (!Null.check(ct.getCurrency().getCode())) {
                templi.add(ct);
            }
        }
//        ArrayList reportRows = new ArrayList();
//        reportRows.add(templi);
        templi.add(0, new AbroadGroupCost());
        templi.add(templi.size(), new AbroadGroupCost());//空白行
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(templi);//detail  data
        List blist = new ArrayList();
        for (AbroadGroupBackorCollar bl : backLi) {
            if (!Null.check(bl.getCurrency().getCode()) && bl.getSign() != null) {
                blist.add(bl);
            }
        }
        JRBeanCollectionDataSource backorCollar = new JRBeanCollectionDataSource(blist);//detail  data
        map.put("backorCollar", backorCollar);
        map.put("costDetail", dataSource);
        facesContext.responseComplete();

        JasperPrint jasperPrint = JasperFillManager.fillReport(scontext.getRealPath("/page/pay/print/abroadTravelCost.jasper"), map, dataSource);
        jasperPrintList.add(jasperPrint);
//        JasperPrint jasperPrintBill = JasperFillManager.fillReport(scontext.getRealPath("/page/pay/print/bill.jasper"), map);
//        jasperPrintList.add(jasperPrintBill);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JRPdfExporter exporter = new JRPdfExporter();
        //exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintList);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
        exporter.exportReport();

        byte[] bytes = baos.toByteArray();

        if (bytes != null && bytes.length > 0) {
            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition", "inline; filename=\"relatorioPorData.pdf\"");
            response.setContentLength(bytes.length);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes, 0, bytes.length);
            outputStream.flush();
            outputStream.close();
        }
    }

    private Map reportParameter() {
        Integer days;
        Map map = new HashMap();
        map.put("numDate", abroad.getNumDate());
        map.put("number", abroad.getNumber());
        map.put("member", abroad.getGroup().getMember());
        map.put("person", abroad.getPerson());
        map.put("costType", abroad.getCostType());//支出类别
        map.put("projname", abroad.getProject().getFinName());
        map.put("affair", abroad.getAffair());//事由
        map.put("country", abroad.getGroup().getCountry());
        map.put("startDate", abroad.getGroup().getStartDate());
        map.put("endDate", abroad.getGroup().getEndDate());
        days = Integer.parseInt(((abroad.getGroup().getEndDate().getTime() - abroad.getGroup().getStartDate().getTime()) / (1000 * 60 * 60 * 24)) + "");
        //System.out.println("days+ :" + days);
        if (days.equals(0)) {
            map.put("days", 1);
        } else {
            map.put("days", days);
        }
        map.put("affixAmount", abroad.getAffixAmount());//附单据张数
        map.put("currencyName", cost.getCurrency().getName());//币种
        map.put("stayCost", cost.getStayCost());
        map.put("foodCost", cost.getFoodCost());
        map.put("mixCost", cost.getMixCost());
        map.put("personalCost", cost.getPersonalCost());
        map.put("trafficCost", cost.getTrafficCost());
        map.put("other", cost.getOther());
        // map.put("total", cost.getOther() + cost.getTrafficCost() + cost.getPersonalCost() + cost.getMixCost() + cost.getFoodCost() + cost.getStayCost());
        map.put("currency", back.getCurrency().getName());//预借币种
        map.put("advance", back.getAdvance());//预借金额
        map.put("sign", back.getSign());//退或领
        map.put("amount", back.getAmount());//退（领）金额
        //补充粘贴单参数
        map.put("deptname", abroad.getPayDept().getName());
        map.put("cpsn_name", abroad.getUser().getCpsn_name());
        map.put("total", setStrTotal());
        map.put("isBaseCost", isBaseCost());//是基本支出
        //
        System.out.println("isBaseCost : " + isBaseCost());
        System.out.println("proj costType : " + abroad.getProject().getCostType());
        return map;
    }

    private String isBaseCost() {
        if (abroad.getProject() == null || abroad.getProject().getCostType() == null) return "-1";
        else if (abroad.getProject().getCostType() == 1) return "0";
        else if (abroad.getProject().getCostType() == 0) return "1";
        else return "";
    }

    private String setStrTotal() {
        DecimalFormat dcmFmt = new DecimalFormat("0.00");
        String strTotal = "";
        int indexf = 0;
        Double total = 0d;
        List<Expense> li = new ArrayList<Expense>();
        for (int i = 1; i < costLi.size(); i++) {
            if (costLi.get(indexf).getCurrency().getCode().equals(costLi.get(i).getCurrency().getCode())) {
                total += Null.convert(costLi.get(i).getStayCost())
                        + Null.convert(costLi.get(i).getFoodCost())
                        + Null.convert(costLi.get(i).getMixCost())
                        + Null.convert(costLi.get(i).getPersonalCost())
                        + Null.convert(costLi.get(i).getTrafficCost())
                        + Null.convert(costLi.get(i).getOther());
            } else {
                total = total + Null.convert(costLi.get(indexf).getStayCost())
                        + Null.convert(costLi.get(indexf).getFoodCost())
                        + Null.convert(costLi.get(indexf).getMixCost())
                        + Null.convert(costLi.get(indexf).getPersonalCost())
                        + Null.convert(costLi.get(indexf).getTrafficCost())
                        + Null.convert(costLi.get(indexf).getOther());
                Expense travel = new Expense();
                travel.getCurrency().setName(costLi.get(indexf).getCurrency().getName());
                travel.setTotal(total);
                li.add(travel);
                indexf = i;
                total = 0d;
            }
            if (i == costLi.size() - 1) {
                total = total + Null.convert(costLi.get(indexf).getStayCost())
                        + Null.convert(costLi.get(indexf).getFoodCost())
                        + Null.convert(costLi.get(indexf).getMixCost())
                        + Null.convert(costLi.get(indexf).getPersonalCost())
                        + Null.convert(costLi.get(indexf).getTrafficCost())
                        + Null.convert(costLi.get(indexf).getOther());
                Expense travel = new Expense();
                travel.getCurrency().setName(costLi.get(indexf).getCurrency().getName());
                travel.setTotal(total);
                li.add(travel);
            }
        }
        for (Expense l : li) {
            strTotal += l.getCurrency().getName().trim() + ":" + dcmFmt.format(l.getTotal()) + ";";
        }
        if (strTotal.length() > 0) {
            return strTotal.substring(0, strTotal.length() - 1);
        }
        return "";
    }

    public void exportExcel() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("个人单据出国差旅费报销单列表");
        String[] excelColumns = initTabeleHeader();
        List<Expense> rows = abroadList;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("个人单据出国差旅费报销单列表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (Expense row : rows) {
            createTableRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        TravelInputBean.exportExcel(demoWorkBook, demoSheet);

    }

    //初始化表头信息
    public String[] initTabeleHeader() {
        String[] excelColumns = {"单据编号", "单据状态", "单据日期", "出差事由", "报销金额", "预算项目", "报销人", "部门", "支出类别", "预算来源",
            "经济分类", "支出渠道", "支付令", "核定金额", "审核日期", "审核人", "支付金额", "支付日期", "出纳"};
        return excelColumns;
    }

    public static void createTableRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, Expense eit, int rowIndex) {
        //创建第rowIndex行
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        dstyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));//格式
        HSSFCell cell;
        HSSFRow row = demoSheet.createRow(rowIndex);

        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(eit.getNumber()));
        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.functionNumberStatus().get(eit.getNumberStatus())));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertDate(eit.getNumDate()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(3);
        cell.setCellValue(PayCodeConstants.convertString(eit.getAffair()));
        cell = row.createCell(4);
        cell.setCellValue(PayCodeConstants.convertDouble(eit.getTotal()));
        cell = row.createCell(5);
        cell.setCellValue(PayCodeConstants.convertString(eit.getProject().getFinName()));
        cell = row.createCell(6);
        cell.setCellValue(PayCodeConstants.convertString(eit.getUser().getCpsn_name()));
        cell = row.createCell(7);
        cell.setCellValue(PayCodeConstants.convertString(eit.getDept().getName()));
        cell = row.createCell(8);
        cell.setCellValue(PayCodeConstants.convertString(eit.getCostClass()));
        cell = row.createCell(9);
        cell.setCellValue(PayCodeConstants.convertString(eit.getBudgetSource()));
        cell = row.createCell(10);
        cell.setCellValue(PayCodeConstants.convertString(eit.getCostitem().getName()));
        cell = row.createCell(11);
        cell.setCellValue(PayCodeConstants.convertString(eit.getCostTypes().getName()));
        cell = row.createCell(12);
        cell.setCellValue(PayCodeConstants.convertString(eit.getPaycode()));

        cell = row.createCell(13);
        cell.setCellValue(PayCodeConstants.convertDouble(eit.getCheckaccount()));
        cell = row.createCell(14);
        if (eit.getAuditDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(eit.getAuditDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(15);
        cell.setCellValue(PayCodeConstants.convertString(eit.getAuditor()));
        cell = row.createCell(16);
        cell.setCellValue(PayCodeConstants.convertDouble(eit.getPayaccount()));
        cell = row.createCell(17);
        if (eit.getPayDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(eit.getPayDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(18);
        cell.setCellValue(PayCodeConstants.convertString(eit.getPayer()));

    }

    public static void exportExcel(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    //getter and setter
    public Expense getAbroad() {
        return abroad;
    }

    public void setAbroad(Expense abroad) {
        this.abroad = abroad;
    }

    public ClassCode getClasscode() {
        return classcode;
    }

    public void setClasscode(ClassCode classcode) {
        this.classcode = classcode;
    }

    public List<ClassCode> getClasslist() {
        return classlist;
    }

    public void setClasslist(List<ClassCode> classlist) {
        this.classlist = classlist;
    }

    public LinkedList<Expense> getLinkedli() {
        return linkedli;
    }

    public void setLinkedli(LinkedList<Expense> linkedli) {
        this.linkedli = linkedli;
    }

    public List<Expense> getAbroadList() {
        return abroadList;
    }

    public void setAbroadList(List<Expense> abroadList) {
        this.abroadList = abroadList;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public DataModel<Expense> getAbroadModel() {

        return abroadModel;
    }

    public void setAbroadModel(DataModel abroadModel) {
        this.abroadModel = abroadModel;
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public AbroadGroupBackorCollar getBack() {
        return back;
    }

    public void setBack(AbroadGroupBackorCollar back) {
        this.back = back;
    }

    public List<AbroadGroupBackorCollar> getBackLi() {
        return backLi;
    }

    public void setBackLi(List<AbroadGroupBackorCollar> backLi) {
        this.backLi = backLi;
    }

    public DataModel<AbroadGroupBackorCollar> getBackModel() {
        return backModel;
    }

    public void setBackModel(DataModel backModel) {
        this.backModel = backModel;
    }

    public AbroadGroupCost getCost() {
        return cost;
    }

    public void setCost(AbroadGroupCost cost) {
        this.cost = cost;
    }

    public List<AbroadGroupCost> getCostLi() {
        return costLi;
    }

    public void setCostLi(List<AbroadGroupCost> costLi) {
        this.costLi = costLi;
    }

    public int getCostLiSize() {
        return costLiSize;
    }

    public void setCostLiSize(int costLiSize) {
        this.costLiSize = costLiSize;
    }

    public DataModel<AbroadGroupCost> getCostModel() {
        return costModel;
    }

    public void setCostModel(DataModel costModel) {
        this.costModel = costModel;
    }

    public AbroadGroupCurrency getCurrency() {
        return currency;
    }

    public void setCurrency(AbroadGroupCurrency currency) {
        this.currency = currency;
    }

    public List<AbroadGroupCurrency> getCurrencyLi() {
        return currencyLi;
    }

    public void setCurrencyLi(List<AbroadGroupCurrency> currencyLi) {
        this.currencyLi = currencyLi;
    }

    public boolean isDeleteable() {
        return deleteable;
    }

    public void setDeleteable(boolean deleteable) {
        this.deleteable = deleteable;
    }

    public UIDataTable getDeptData() {
        return deptData;
    }

    public void setDeptData(UIDataTable deptData) {
        this.deptData = deptData;
    }

    public List<Department> getDeptli() {
        return deptli;
    }

    public void setDeptli(List<Department> deptli) {
        this.deptli = deptli;
    }

    public Disabled getDis() {
        return dis;
    }

    public void setDis(Disabled dis) {
        this.dis = dis;
    }

    public AbroadGroupGroup getGroup() {
        return group;
    }

    public void setGroup(AbroadGroupGroup group) {
        this.group = group;
    }

    public List<AbroadGroupGroup> getGroupLi() {
        return groupLi;
    }

    public void setGroupLi(List<AbroadGroupGroup> groupLi) {
        this.groupLi = groupLi;
    }

    public List<SelectItem> getPayStyleList() {
        return payStyleList;
    }

    public void setPayStyleList(List<SelectItem> payStyleList) {
        this.payStyleList = payStyleList;
    }

    public List<PayStyle> getPayStyleli() {
        return payStyleli;
    }

    public void setPayStyleli(List<PayStyle> payStyleli) {
        this.payStyleli = payStyleli;
    }

    public String getPayWay() {
        return payWay;
    }

    public void setPayWay(String payWay) {
        this.payWay = payWay;
    }

    public boolean isPrintAble() {
        return printAble;
    }

    public void setPrintAble(boolean printAble) {
        this.printAble = printAble;
    }

    public QueryVouchers getQta() {
        return qta;
    }

    public void setQta(QueryVouchers qta) {
        this.qta = qta;
    }

    public boolean isSaveOrNot() {
        return saveOrNot;
    }

    public void setSaveOrNot(boolean saveOrNot) {
        this.saveOrNot = saveOrNot;
    }

    public boolean isShowAble() {
        return showAble;
    }

    public void setShowAble(boolean showAble) {
        this.showAble = showAble;
    }

    public boolean isSubmitOrNot() {
        return submitOrNot;
    }

    public void setSubmitOrNot(boolean submitOrNot) {
        this.submitOrNot = submitOrNot;
    }

    public boolean isUpdateOrNot() {
        return updateOrNot;
    }

    public void setUpdateOrNot(boolean updateOrNot) {
        this.updateOrNot = updateOrNot;
    }

    public boolean isBrowAble() {
        return browAble;
    }

    public void setBrowAble(boolean browAble) {
        this.browAble = browAble;
    }

    public DataModel getDeptModel() {
        return deptModel;
    }

    public void setDeptModel(DataModel deptModel) {
        this.deptModel = deptModel;
    }

    private String curPerNum() {
        return LoginParam.getPer().getCpsn_number();
    }

    private String curPerName() {
        return LoginParam.getPer().getCpsn_name();
    }

    private String curDeptCode() {
        return LoginParam.getDept().getCode();
    }

    private String curDeptName() {
        return LoginParam.getDept().getName();
    }

    private Date curLoginDate() {
        return LoginParam.getLoginDate();
    }

    private Integer curIyear() {
        return LoginParam.getIyear();
    }

    private String curOrgCode() {
        return LoginParam.getOrg().getCode();
    }

    public FinancialProject getFinProj() {
        return finProj;
    }

    public void setFinProj(FinancialProject finProj) {
        this.finProj = finProj;
    }

    public DataModel<FinancialProject> getFinProjModel() {
        return finProjModel;
    }

    public void setFinProjModel(DataModel<FinancialProject> finProjModel) {
        this.finProjModel = finProjModel;
    }

    public String getProjParam() {
        return projParam;
    }

    public void setProjParam(String projParam) {
        this.projParam = projParam;
    }

    public List<SelectItem> getPerli() {
        //if (perli == null) queryPerLi();
        return perli;
    }

    public void setPerli(List<SelectItem> perli) {
        this.perli = perli;
    }
}
